﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ShareMarking.Entity;
using System.Web;
using ShareMarking.Systems.Service;
using System.Drawing;
using ZXing;
using ZXing.QrCode.Internal;
using ZXing.Common;
using System.Drawing.Imaging;
using System.IO;
using ShareMarking.Service;

namespace ShareMarking.Interface
{
    public class Qrcode_diy : ManagePage
    {       
        //string pst = "http://api.k780.com:88/?app=shorturl.set&url=" + text + "&appkey=" + API_APPKEY + "&sign=" + API_SECRET + "&format=json";
        //<add key="short_httpstr" value="http://api.k780.com:88/?app=shorturl.set"/>
        //<add key="short_appkey" value="20631"/>
        //<add key="short_signsecret" value="1186483b6aa2626179b0843e208928ef"/>
        protected string httpstr;
        protected string appkey;
        protected string signserect;

        protected string cliUrl;
        protected string mhid;

        protected string UrlStr;//跳转路径

        //现用接口（Zxing组件）
        public Qrcode_diy(string UrlStr)
        {
            this.UrlStr = UrlStr;
        }
        //草料接口 （已弃用）
        public Qrcode_diy(string cliUrl, string mhid)
        {
            this.cliUrl = cliUrl;
            this.mhid = mhid;
        }
        //NowApi接口（https://www.nowapi.com/）已弃用
        public Qrcode_diy(string httpstr, string appkey, string signserect)
        {
            this.httpstr = httpstr;
            this.appkey = appkey;
            this.signserect = signserect;
        }

        public string CreateQrCode(string text)
        {
            #region sign 已弃用

            var parameters = new Dictionary<string, string>();
            parameters.Add("text", text);
            parameters.Add("mhid", this.mhid);
            var post = BuildQuery2(parameters);
            #endregion

            var postData = Encoding.UTF8.GetBytes(post);
            ComLib.WebClientHelper click = new ComLib.WebClientHelper();
            click.Encoding = Encoding.UTF8;

            byte[] result = click.GetData(this.cliUrl + post);//请求处理，返回结果
            //var resultentity = ComLib.JsonHelper.JsonDeserialize<ShareMarking.Entity.resultshorturl>(result);
            string recordString= Encoding.UTF8.GetString(result).TrimEnd('\0');

            var resultentity = recordString;
            return resultentity;
        }
       
        #region 请求NowApi接口（已弃用）
        public resultshorturl CreateShortUrl(string message, string diyurl)
        {
            #region sign 已弃用
            //var timestamp = DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss");

            //var parameters = new Dictionary<string, string>();
            //parameters.Add("message", ComLib.JsonHelper.JsonSerializer<message>(message));
            //parameters.Add("method", "001");
            //parameters.Add("timestamp", timestamp);

            //var request_str = BuildQuery(parameters) + this.signserect;
            //var signature = ComLib.DEncrypt.MD5ForPHP(request_str.ToLower());
            //parameters.Add("sign", signature);
            #endregion
            string posturl = HttpUtility.UrlEncode(message, Encoding.UTF8);//UrlEncode编码
            var parameters = new Dictionary<string, string>();
            parameters.Add("url", posturl);
            parameters.Add("appkey", this.appkey);
            parameters.Add("sign", this.signserect);
            parameters.Add("format", "json");
            parameters.Add("fixed", diyurl);//指定短网址内容
            var pst = BuildQuery2(parameters).ToString();
            //{"success":"0","msgid":"1000553","msg":"sign效验失败"}
            //{"success":"0","msgid":"1030003","msg":"fixed参数有误"}            
            var postData = Encoding.UTF8.GetBytes(pst);
            ComLib.WebClientHelper click = new ComLib.WebClientHelper();
            click.Encoding = Encoding.UTF8;
            string result = click.Post(this.httpstr, postData);//请求处理，返回结果
            var resultentity = ComLib.JsonHelper.JsonDeserialize<ShareMarking.Entity.resultshorturl>(result);
            return resultentity;
        }
        #endregion

        #region 生成带Logo的二维码
        /// <summary>
        /// 生成带Logo的二维码
        /// </summary>
        /// <param name="text"></param>
        public string GenerateQrCodeImg(string text)
        {
            string url = "";
            string qrcontent = text;//返回短码url
            //var resultentity = "";
            string newFilePath = "";
            ComLib.LogLib.Log4NetBase.Log("1、====开始创建无参活动二维码========请求的参数:" + qrcontent);
            resultdiy resultdiy = new resultdiy();
            try
            {
                if (!qr_DiyCodeService.Instance.Get_IsExist_ByWhere(qr_DiyCode._.code_url == qrcontent))
                {

                    #region zxing生成二维码
                    //Logo 图片
                    string AVATAR_Dir = @"/images/MZCLOGO.png";
                    string UpLoadPath = Utils.GetMapPath(AVATAR_Dir); //上传目录的物理路径
                    Bitmap logo = new Bitmap(UpLoadPath);

                    //构造二维码写码器
                    MultiFormatWriter writer = new MultiFormatWriter();
                    Dictionary<EncodeHintType, object> hint = new Dictionary<EncodeHintType, object>();
                    hint.Add(EncodeHintType.MARGIN, 2);  //去白
                    hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
                    hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

                    //生成二维码 
                    BitMatrix bm = writer.encode(qrcontent, BarcodeFormat.QR_CODE, 430, 430, hint);
                    BarcodeWriter barcodeWriter = new BarcodeWriter();
                    Bitmap map = barcodeWriter.Write(bm);


                    //获取二维码实际尺寸（去掉二维码两边空白后的实际尺寸）
                    int[] rectangle = bm.getEnclosingRectangle();

                    //计算插入图片的大小和位置
                    int middleW = Math.Min((int)(rectangle[2] / 3.5), logo.Width);
                    int middleH = Math.Min((int)(rectangle[3] / 3.5), logo.Height);
                    int middleL = (map.Width - middleW) / 2;
                    int middleT = (map.Height - middleH) / 2;

                    //将img转换成bmp格式，否则后面无法创建Graphics对象
                    Bitmap bmpimg = new Bitmap(map.Width, map.Height, PixelFormat.Format32bppArgb);
                    using (Graphics g = Graphics.FromImage(bmpimg))
                    {
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        g.DrawImage(map, 0, 0);
                    }
                    //将二维码插入图片
                    Graphics myGraphic = Graphics.FromImage(bmpimg);
                    //白底
                    myGraphic.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH);
                    myGraphic.DrawImage(logo, middleL, middleT, middleW, middleH);

                    #endregion

                    #region 保存成图片

                    string newFileName = GetRamCode() + ".png"; //随机生成新的文件名
                    string upLoadPath = GetUpLoadPath(); //保存目录相对路径
                    string fullUpLoadPath = Utils.GetMapPath(upLoadPath); //保存目录的物理路径
                    newFilePath = Utils.GetMapPath(upLoadPath + newFileName); //保存后的路径
                    url = upLoadPath + newFileName;
                    //url = newFilePath;
                    //检查保存的物理路径是否存在，不存在则创建
                    if (!Directory.Exists(fullUpLoadPath))
                    {
                        Directory.CreateDirectory(fullUpLoadPath);
                    }
                    bmpimg.Save(newFilePath, ImageFormat.Png);

                    //resultentity = "{\"subcode\":\"00\",\"msg\":\"请求成功！\",\"result\":\"" + url + "\"}";
                    resultdiy.subcode = "00";
                    resultdiy.msg = "请求成功！";
                    resultdiy.result = url;
                    ComLib.LogLib.Log4NetBase.Log("2、====创建二维码成功！========请求的参数:" + qrcontent + "//生成路径:" + newFilePath);
                    #endregion
                }
                else
                {
                    //resultentity = "{\"subcode\":\"01\",\"msg\":\"此码已存在！\",\"result\":\"" + qrcontent + "\"}";
                    resultdiy.subcode = "01";
                    resultdiy.msg = "此码已存在！";
                    resultdiy.result = qrcontent;
                    ComLib.LogLib.Log4NetBase.Log("3、====创建二维码失败========此码已存在！" + qrcontent);
                }
                ComLib.LogLib.Log4NetBase.Log("3、====创建二维码结束========//生成路径:" + newFilePath);
            }
            catch (Exception ex)
            {
                //resultentity = "{\"subcode\":\"03\",\"msg\":\"请求失败！\",\"result\":\"" + ex.Message + "\"}";
                resultdiy.subcode = "03";
                resultdiy.msg = "请求失败！数据异常";
                resultdiy.result = "数据异常";
                ComLib.LogLib.Log4NetBase.Log("3、====创建二维码失败========请求的URL:" + text + "::==错误信息==" + ex.StackTrace);
            }
            return ComLib.JsonHelper.JsonSerializer<resultdiy>(resultdiy);
        }
        #endregion

        #region 生成日期随机码
        /// <summary>
        /// 生成日期随机码
        /// </summary>
        /// <returns></returns>
        public static string GetRamCode()
        {
            #region
            return DateTime.Now.ToString("HHmmssffff");
            #endregion
        }
        #endregion

        #region 返回上传目录相对路径
        /// <summary>
        /// 返回上传目录相对路径
        /// </summary>
        /// <param name="fileName">上传文件名</param>
        private string GetUpLoadPath()
        {
            string path = siteConfig.webpath + siteConfig.filepath + "/"; //站点目录+上传目录
            switch (this.siteConfig.filesave)
            {
                case 1: //按年月日每天一个文件夹
                    path += DateTime.Now.ToString("yyyyMMdd");
                    break;
                default: //按年月/日存入不同的文件夹
                    path += DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd");
                    break;
            }
            return path + "/";
        }
        #endregion

        #region 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        public static string BuildQuery2(IDictionary<string, string> parameters)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;

            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名为空的参数
                if (!string.IsNullOrEmpty(name))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }

                    postData.Append(name);
                    postData.Append("=");
                    //if (name == "message")
                    //{
                    //    postData.Append(HttpUtility.UrlEncode(value));
                    //}
                    //else
                    //{
                    postData.Append(value);
                    //}
                    hasParam = true;
                }
            }

            return postData.ToString();
        }
        #endregion
    }
}
